import { ref } from "vue";
import { useCrudForm } from "@/composables/useCrudForm";
import { staffNeedFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrStaffNeedRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrStaffNeedRequestBill,
  ISysHrStaffNeedRequestBillVm,
  ISysHrStaffNeedRequestBillEntryView,
} from "../api/interface";

/**
 * 用人需求申请信息专用 Composable
 */
export function useStaffNeedInfo() {
  // 创建API实例
  const api = SysHrStaffNeedRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
  };

  // 选项数据加载器
  const optionLoaders = {
    group: async (): Promise<{ Value: string; Text: string; }[]> => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    company: async (): Promise<{ Value: string; Text: string; }[]> => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetUserCompanies();
      // 直接返回公司列表接口的数据
      return result;
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrStaffNeedRequestBill, ISysHrStaffNeedRequestBillVm>(
    staffNeedFormConfig,
    apiConfig,
    optionLoaders
  );

  // 初始化时设置公司字段默认值
  crudForm.formData.company = '';

  // 明细列表状态
  const detailList = ref<ISysHrStaffNeedRequestBillEntryView[]>([]);
  const detailLoading = ref(false);

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
    approvalOpinion: "ApprovalOpinion",

    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 工作信息
    company: "CompanyName", // 映射到我们设置的公司名称字段
    group: "Group.GroupName", // 直接映射到部门名称
  };

  /**
   * 加载用人需求申请详情数据
   */
  const loadStaffNeedDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
            // 日期字段处理（保留用于可能的格式化需求）
          }
        });

        // 先使用通用转换
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        // 添加特殊处理，确保选择器字段正确映射
        await ensurePickerFieldsMapping(detail);


        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      console.error("获取用人需求申请详情失败:", error);
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理公司 - 通过详情接口的OrgId匹配公司列表的Value，显示对应的Text
    if (apiData.OrgId) {
      // 优先从已缓存的选项数据中查找
      if (staffNeedFormConfig.company?.optionsData) {
        const companyOption = staffNeedFormConfig.company.optionsData.find(
          (item: any) => item.value === apiData.OrgId
        );
        if (companyOption) {
          crudForm.formData.company = companyOption.text;
          crudForm.pickerValues.company = companyOption.value;
          // 同时设置到 originalData 中，以便 XenDynamicDetailsCard 组件能显示
          if (crudForm.originalData.value) {
            crudForm.originalData.value.CompanyName = companyOption.text;
          }
          return; // 找到就直接返回
        }
      }

      // 如果缓存中没找到，重新调用公司接口
      const commonApiInstance = commonApi();
      try {
        const companies = await commonApiInstance.GetUserCompanies();
        const companyOption = companies.find((item: any) => item.Value === apiData.OrgId);

        if (companyOption) {
          crudForm.formData.company = companyOption.Text;
          crudForm.pickerValues.company = companyOption.Value;
          // 同时设置到 originalData 中，以便 XenDynamicDetailsCard 组件能显示
          if (crudForm.originalData.value) {
            crudForm.originalData.value.CompanyName = companyOption.Text;
          }
        }
      } catch (error) {
        console.error('重新加载公司数据失败:', error);
      }
    }

    // 处理部门
    if (apiData.GroupId && staffNeedFormConfig.group?.optionsData) {
      const groupOption = staffNeedFormConfig.group.optionsData.find(
        (item: any) => item.value === apiData.GroupId
      );
      if (groupOption) {
        crudForm.formData.group = groupOption.text;
        crudForm.pickerValues.group = groupOption.value;
      }
    }

    // 处理单据状态显示
    if (apiData.BillStatus !== undefined) {
      crudForm.formData.billStatus = apiData.BillStatus || "";
    }

    // 处理状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 部门名称已通过字段映射直接处理，无需特殊处理

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }
  };

  /**
   * 获取用人需求明细列表
   */
  const loadDetailList = async (hrStaffNeedId: string): Promise<void> => {
    detailLoading.value = true;
    try {
      const response = await api.searchList({
        HrStaffNeedId: hrStaffNeedId,
        Limit: 9999, // 一次性获取所有明细数据
        Page: 1,
      });

      if (response && response.Data) {
        detailList.value = response.Data;
      } else {
        detailList.value = [];
      }
    } catch (error) {
      console.error("获取用人需求明细失败:", error);
      detailList.value = [];
    } finally {
      detailLoading.value = false;
    }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 用人需求申请信息专用方法
    loadStaffNeedDetail,

    // 明细列表相关
    detailList,
    detailLoading,
    loadDetailList,

    // 字段映射
    fieldMapping,
  };
}
